package com.vehicle.controller;
import com.vehicle.bean.Admin;
import com.vehicle.exception.VehicleException;
import com.vehicle.form.AdminResetForm;
import com.vehicle.form.AdminLoginForm;
import com.vehicle.form.CodeForm;
import com.vehicle.mapper.UserLogMapper;
import com.vehicle.result.ResponseEnum;
import com.vehicle.service.AdminService;
import com.vehicle.util.JwtUtil;
import com.vehicle.util.LogUtil;
import com.vehicle.vo.AdminLoginVO;
import com.vehicle.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 校园车辆管理系统
 * @since 2023-04-17
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    UserLogMapper userLogMapper;

    /**
     * 管理员登陆
     * @param request
     * @param adminForm
     * @return ResultVO
     */
    //管理员登录：用户名，密码
    @PostMapping("/login")
    public ResultVO login(HttpServletRequest request,@RequestBody AdminLoginForm adminForm){
        String ip = request.getRemoteAddr();
        System.out.println("从前端收到的内容为："+adminForm);
        Admin admin = adminService.getAdminByName(adminForm.getAdminName());
        //检验密码
        if(!admin.getPassword().equals(adminForm.getPassword())){
            userLogMapper.insert(LogUtil.insertAdminLogin(admin.getAdminId(),"密码检验失败",ip,"失败"));
            throw new VehicleException(ResponseEnum.PASSWORD_ERROR.getMsg());
        }
        //生成token
        String token = JwtUtil.createToken(admin.getAdminId(),admin.getAdminName());
        //设置返回前端的内容
        AdminLoginVO adminVO = adminService.getLoginMessage(admin);
        //修改数据库里面的token
        boolean b = adminService.updatePasswordOrTokenById(admin.getAdminId(),null,token);
        if(b){
            userLogMapper.insert(LogUtil.insertAdminLogin(admin.getAdminId(),"登陆成功",ip,"成功"));
            return ResultVO.succ(adminVO);
        }
        userLogMapper.insert(LogUtil.insertAdminLogin(admin.getAdminId(),"登陆失败",ip,"失败"));
        return ResultVO.fail("登陆失败");
    }

    //重置密码，电话，旧密码，新密码
    @PutMapping("/resetPassword")
    public ResultVO resetPassword(HttpServletRequest request,AdminResetForm adminResetForm){
        String ip = request.getRemoteAddr();
        String id = request.getHeader("id");
        Admin admin = adminService.getAdminByTelAndPassword(adminResetForm.getTel(),adminResetForm.getOldPassword());
        boolean b = adminService.updatePasswordOrTokenById(admin.getAdminId(), adminResetForm.getNewPassword(),null);
        if(redisTemplate.hasKey("sms-code"+adminResetForm.getTel())){
            String getCode = (String) redisTemplate.opsForValue().get("sms-code"+adminResetForm.getTel());
            if(b && (getCode == adminResetForm.getCode())){
                userLogMapper.insert(LogUtil.insertAdminUpdate(Integer.parseInt(id),"重置成功",ip,"成功"));
                return ResultVO.succ(null);
            }
            userLogMapper.insert(LogUtil.insertAdminUpdate(Integer.parseInt(id),"重置失败",ip,"失败"));
            return ResultVO.fail("重置失败");
        }
        userLogMapper.insert(LogUtil.insertAdminUpdate(Integer.parseInt(id),"验证码已过期",ip,"失败"));

        return ResultVO.fail("验证码已过期");

    }
    //忘记密码：电话，新密码
    @PutMapping("/forgetPassword")
    public ResultVO forgetPassword(HttpServletRequest request,@RequestBody CodeForm codeForm){
        String ip = request.getRemoteAddr();
        System.out.println(codeForm);
        Admin admin = adminService.getAdminByTel(codeForm.getTel());
        boolean b = adminService.updatePasswordOrTokenById(admin.getAdminId(),codeForm.getPassword(),null);
        System.out.println(redisTemplate.hasKey("sms-code"+codeForm.getTel()));
        if(redisTemplate.hasKey("sms-code"+codeForm.getTel())){
            System.out.println("在这里丫丫");
            System.out.println(redisTemplate.opsForValue().get("sms-code"+codeForm.getTel()));
            String getCode = (String) redisTemplate.opsForValue().get("sms-code"+codeForm.getTel());
            if(b){
                if(getCode.equals(codeForm.getCode())){
                    userLogMapper.insert(LogUtil.insertAdminUpdate(admin.getAdminId(),"更新密码",ip,"成功"));
                    return ResultVO.succ(null);
                }
                userLogMapper.insert(LogUtil.insertAdminUpdate(admin.getAdminId(),"验证码不对",ip,"失败"));
                return ResultVO.fail("重置失败");
            }
            userLogMapper.insert(LogUtil.insertAdminUpdate(admin.getAdminId(),"更新密码失败",ip,"失败"));
            return ResultVO.fail("重置失败");
        }
        userLogMapper.insert(LogUtil.insertAdminUpdate(admin.getAdminId(),"验证码过期",ip,"失败"));
        return ResultVO.fail("验证码过期");
    }



//    检查token
    @GetMapping("/checkToken")
    public ResultVO checkToken(HttpServletRequest request){
        String token = request.getHeader("token");
        boolean result = JwtUtil.checkToken(token);
        if(result) return ResultVO.succ(null);
        return ResultVO.fail(ResponseEnum.TOKEN_ERROR.getMsg());
    }

    @GetMapping("/adminList/{page}/{size}")
    public ResultVO getAdminList(@PathVariable("page") String page,@PathVariable("size") String size){
        return ResultVO.succ(adminService.adminList(Integer.parseInt(page),Integer.parseInt(size)));
    }

    @GetMapping("/adminList/{searchValue}")
    public ResultVO getAdminListBySearchContent(@PathVariable("searchValue") String searchValue){
        return ResultVO.succ(adminService.getListByContent(searchValue));
    }


    @PostMapping("/addAdmin")
    public ResultVO addAdmin(HttpServletRequest request,@RequestBody Admin admin){
        String ip = request.getRemoteAddr();
        String adminId = request.getHeader("id");
        boolean b = adminService.adminNameExist(admin.getAdminName());
        if(b){
            boolean b1 = adminService.adminTelExist(admin.getTel());
            if(b1){
                userLogMapper.insert(LogUtil.insertAdminInsert(Integer.parseInt(adminId),"添加用户成功",ip,"成功"));
                return ResultVO.succ(adminService.addAdminMessage(admin));
            }
            userLogMapper.insert(LogUtil.insertAdminInsert(Integer.parseInt(adminId),"该手机号已存在",ip,"失败"));
            return ResultVO.fail("该手机号已存在");
        }
        userLogMapper.insert(LogUtil.insertAdminInsert(Integer.parseInt(adminId),"该用户名已存在",ip,"失败"));
        return ResultVO.fail("该用户名已存在");
    }

    @DeleteMapping("/{adminId}")
    public ResultVO deleteAdmin(HttpServletRequest request,@PathVariable("adminId") Integer adminId){
        String ip = request.getRemoteAddr();
        String id = request.getHeader("id");
        boolean b = adminService.deleteAdminById(adminId);
        if(b){
            userLogMapper.insert(LogUtil.insertAdminDelete(Integer.parseInt(id),"删除成功",ip,"成功"));
            return ResultVO.succ("删除成功");
        }
        userLogMapper.insert(LogUtil.insertAdminDelete(Integer.parseInt(id),"删除失败",ip,"失败"));
        return ResultVO.fail("删除失败");
    }

}

